﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ProgNetComponentsDx.Options;
using ProgNetComponentsDx.Browsers;
using ProgNetComponents.Classes;
using Wydatki.Setup.Lotto;
using ProgNetComponentsDx.Forms;
using DevExpress.XtraBars;

namespace Wydatki
{
    public partial class Form1 : HideToTrayForm
    {
        private Browser lataPodatkowe;
        private Browser BrowserLataPodatkowe
        {
            get
            {
                if (lataPodatkowe == null)
                {
                    lataPodatkowe = BrowserCache.GetBrowser(Init.InitFormBrowserNames.Glowna.LataPodatkowe);
                }
                return lataPodatkowe;
            }
        }

        private Browser _BrowserWrkWyborKombinacjiGrupy;
        private Browser BrowserWrkWyborKombinacjiGrupy
        {
            get
            {
                if (_BrowserWrkWyborKombinacjiGrupy == null)
                {
                    _BrowserWrkWyborKombinacjiGrupy = BrowserCache.GetBrowser(Init.InitFormBrowserNames.Glowna.WrkWyborKombinacjiGrupy);
                }
                return _BrowserWrkWyborKombinacjiGrupy;
            }
        }

        public Form1()
        {
            InitializeComponent();
            Tools.Globals.MdiHelper = mdiHelper1;
            this.xtraTabbedMdiManager1.SetMinTabSize(120);
        }

        #region Ustawienia
        
        private void bbiWyglad_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ProgNetComponentsDx.Forms.FormSkinChooser.ShowSkinChooserDialog() == System.Windows.Forms.DialogResult.OK)
            {
                OptionCache.SetOptionValue(Init.InitFormOptionNames.Rozne.Skorka, LookAndFeel.ActiveSkinName);
                OptionCache.SetOptionValue(Init.InitFormOptionNames.Rozne.Styl, LookAndFeel.ActiveStyle.ToString());
            }
        }
        
        #endregion

        #region Definicje

        #region wydatki
        private void bbiKategoriwProduktow_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.FormKategorieProduktow>();
        }

        private void bbiProdukty_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.FormProdukty>();
        }

        private void bbiSklepy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.FormSklepy>();
        }
        #endregion

        #region praca
        private void bbiKontrachenci_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.Praca.FormKontrachenci>();
        }

        private void bbiLataPodatkowe_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.Praca.FormLataPodatkowe>();
        }

        private void bbiKpir_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.Praca.FormStpKpir>();
        }

        private void bbiVats_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.Praca.FormStpVats>();
        }

        private void bbiVatz_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.Praca.FormStpVatz>();
        }
        
        private void bbiStpKwotyZus_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ObjectDialogResult dlg = BrowserLataPodatkowe.ShowDialog();
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                mdiHelper1.GetMdiChild<Setup.Praca.FormKwotyZus>(dlg.Value.AsInt());
        }

        #endregion

        #endregion

        #region WRK

        #region wydatki

        private void bbiZakupy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Zakupy.FormZakupy>();
        }

        private void bbiZakupyStatystyki_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Zakupy.FormZakupyStatystyki>();
        }


        #endregion

        #region praca
        private void bbiWrkKpirObecny_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ValidateRokPodatkowy())
                mdiHelper1.GetMdiChild<WRK.Praca.FormWrkKpir>(Settings.RokPodatkowy.Value);
        }
        private void bbiWrkVatsObecny_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ValidateRokPodatkowy())
                mdiHelper1.GetMdiChild<WRK.Praca.FormWrkVats>(Settings.RokPodatkowy.Value);
        }
        private void bbiWrkKpirInne_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ObjectDialogResult dlg = BrowserLataPodatkowe.ShowDialog();
            if(dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                mdiHelper1.GetMdiChild<WRK.Praca.FormWrkKpir>(dlg.Value.AsInt());
        }
        private void bbiwrkVatsInne_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ObjectDialogResult dlg = BrowserLataPodatkowe.ShowDialog();
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                mdiHelper1.GetMdiChild<WRK.Praca.FormWrkVats>(dlg.Value.AsInt());
        }
        private void bbiWrkVatzInne_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ObjectDialogResult dlg = BrowserLataPodatkowe.ShowDialog();
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
                mdiHelper1.GetMdiChild<WRK.Praca.FormWrkVatz>(dlg.Value.AsInt());
        }
        private void bbiWrkVatzObecny_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ValidateRokPodatkowy())
                mdiHelper1.GetMdiChild<WRK.Praca.FormWrkVatz>(Settings.RokPodatkowy.Value);
        }
        #endregion

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (this.IsDesignMode())
                return;

            LockEvents = true;
            object op = OptionCache.GetOptionValue(Init.InitFormOptionNames.Global.RokPodatkowy);
            if (op != null)
            {
                bbiRokPodatkowy.EditValue = op.AsInt();
                Settings.RokPodatkowy = op.AsInt();
            }
            LockEvents = false;
            ShowHide(OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Uruchamianie.RunInTray));
            
            string styl = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne.Styl);
            string skin = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Rozne.Skorka);
            ProgNetComponentsDx.Forms.FormSkinChooser.ApplayStyle(styl, skin);

            string str = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Uruchamianie.OtwieranieForm);
            string[] parts;

            switch (str)
            {
                case "W":
                    parts = OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Uruchamianie.WybraneOtwarteFormy).Split('|');
                    if (parts.Contains(WydatkiGlobals.WybraneFormy.Kontrachenci))
                        mdiHelper1.GetMdiChild<Setup.Praca.FormKontrachenci>();
                    if (parts.Contains(WydatkiGlobals.WybraneFormy.KPiR))
                        mdiHelper1.GetMdiChild<WRK.Praca.FormWrkKpir>();
                    if (parts.Contains(WydatkiGlobals.WybraneFormy.Produkty))
                        mdiHelper1.GetMdiChild<Setup.FormProdukty>();
                    if (parts.Contains(WydatkiGlobals.WybraneFormy.VATS))
                        mdiHelper1.GetMdiChild<WRK.Praca.FormWrkVats>();
                    if (parts.Contains(WydatkiGlobals.WybraneFormy.VATZ))
                        mdiHelper1.GetMdiChild<WRK.Praca.FormWrkVatz>();
                    if (parts.Contains(WydatkiGlobals.WybraneFormy.Wydatki))
                        mdiHelper1.GetMdiChild<Zakupy.FormZakupy>();
                    if (parts.Contains(WydatkiGlobals.WybraneFormy.WydatkiStatystyki))
                        mdiHelper1.GetMdiChild<Zakupy.FormZakupyStatystyki>();
                    break;
                case "O":
                    mdiHelper1.OpenFormsFromString(OptionCache.GetOptionStringValue(Init.InitFormOptionNames.Uruchamianie.OstatnioOtwarteFormy));
                    break;
            }
        } 
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall ||
                e.CloseReason == CloseReason.TaskManagerClosing ||
                e.CloseReason == CloseReason.WindowsShutDown)
            {
                Program.IsExit = true;
            }
            e.Cancel = false;
            if (!Program.IsExit)
            {
                List<IDataForm> changedForms = new List<IDataForm>();
                if (this.MdiChildren != null && MdiChildren.Length > 0)
                {
                    foreach (Form f in MdiChildren)
                    {
                        if (f is IDataForm)
                        {
                            if ((f as IDataForm).HasChanges)
                            {
                                changedForms.Add(f as IDataForm);
                            }
                        }
                    }
                }
                if (changedForms.Count > 0)
                {
                    string msg = "Wykryto nie zapisane zmiany:";
                    foreach (IDataForm i in changedForms)
                    {
                        msg = msg.AppendLine(i.Text.Replace("*", ""));
                    }
                    msg = msg.AppendLine("Chcesz je zapisać?");
                    DialogResult dlg = this.ShowDxYNCQuestionDialog(msg);

                    switch (dlg)
                    {
                        case System.Windows.Forms.DialogResult.Cancel:
                            e.Cancel = true;
                            break;
                        case System.Windows.Forms.DialogResult.No: 
                            break;
                        case System.Windows.Forms.DialogResult.Yes:
                            foreach (IDataForm i in changedForms)
                            {
                                if (i.ValidateAll())
                                {
                                    if (!i.Save())
                                    {
                                        this.ShowDxErrorDialog("Błąd zapisu!");
                                        e.Cancel = true;
                                    }
                                    else
                                    {
                                        (i as Form).Close();
                                    }
                                }
                                else
                                {
                                    this.ShowDxWarningDialog("Błąd validacji.");
                                    e.Cancel = true;
                                }
                                if (e.Cancel)
                                {
                                    this.ActivateMdiChild(i as Form);
                                    break;
                                }
                            }
                            break;
                    }
                }
            }
            base.OnFormClosing(e);
            string str = mdiHelper1.GetOpenedFormsString();
            OptionCache.SetOptionValue(Init.InitFormOptionNames.Uruchamianie.OstatnioOtwarteFormy, str);
        }
        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            base.OnFormClosed(e);
            try
            {
                OptionCache.SaveOptions();
            }
            catch (Exception ex) { ex.Log(); }
            try
            {
                ProgNetComponentsDx.Layout.LayoutGrabber.Instance.SaveLayouts();
            }
            catch (Exception ex) { ex.Log(); }
			Program.IsExit = true;
        }

        #region Lotto
        private void bbiLosowaniaLotto_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<WRK.Lotto.FormWrkLottoLosowania>();
        }
        #endregion

        private void bbiStatystykiLotto_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<WRK.Lotto.FormStatystykiLosowan>();
        }

        private void bbiOpcje_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<Setup.FormOpcje>();
        }

        private void bbiStatystykiGlobalne_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mdiHelper1.GetMdiChild<LottoStatystykiGlobalne>();
        }

        private void bbiLottoLosowanieKombinacji_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ObjectDialogResult dlg = BrowserWrkWyborKombinacjiGrupy.ShowNewDialog();
            if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK)
            {
                mdiHelper1.GetMdiChild<WRK.Lotto.FormLottoWyborKombinacji>(dlg.Value.AsInt(-1));
            }
        }
        
        static public bool ReadBinaryFile(string szPath, ref byte[] buff)
        {
            System.IO.FileStream mStreamR;
            System.IO.BinaryReader mBinaryR;
            long Filelen = 0;
            try
            {
                mStreamR = System.IO.File.OpenRead(szPath);
                Filelen = mStreamR.Length;
                mBinaryR = new System.IO.BinaryReader(mStreamR);
                buff = new byte[Filelen];
                mBinaryR.Read(buff, 0, (int)Filelen);
                mBinaryR.Close();
                mStreamR.Close();
            }
            catch (System.IO.FileNotFoundException e)
            {
                return false;
            }
            catch (System.Exception e)
            {
                return false;
            }
            return true;
        }

        void ShowHide(bool hide)
        {
            if (hide)
                this.HideToTray();
            else
                this.ShowFromTray();
        }
        public override void HideToTray()
        {
            base.HideToTray();
            bbiSchowaj.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            bbiPokaz.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
        }
        public override void ShowFromTray()
        {
            base.ShowFromTray();
            bbiPokaz.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
            bbiSchowaj.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
        }
        private void bbiSchowaj_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowHide(true);
        }

        private void bbiPokaz_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowHide(false);
        }

        private void bbiZamknij_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            
        }

        private void notifyIcon1_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                popupMenu1.ShowPopup(Control.MousePosition);
            }
        }

        private void mdiHelper1_FormCreated(object sender, ProgNetComponents.MDI.FormCreateEventArgs e)
        {
            e.Form.FormClosing += new FormClosingEventHandler(Form_FormClosing);
        }

        void Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.MdiFormClosing)
                e.Cancel = true;
            else if (e.CloseReason == CloseReason.ApplicationExitCall || 
                e.CloseReason == CloseReason.TaskManagerClosing ||
                e.CloseReason == CloseReason.WindowsShutDown)
                Program.IsExit = true;
        }
        private bool LockEvents = false;

        private void bbiRokPodatkowy_EditValueChanged(object sender, EventArgs e)
        {
            if (LockEvents)
                return;

            int? rok = null;
            if(bbiRokPodatkowy.EditValue.IsNotNull())
                rok = bbiRokPodatkowy.EditValue.AsInt();

            Settings.RokPodatkowy = rok;
            OptionCache.SetOptionValue(Init.InitFormOptionNames.Global.RokPodatkowy, rok, true,true);
        }

        private bool ValidateRokPodatkowy()
        {
            bool res = true;
            if (Settings.RokPodatkowy == null)
            {
                this.ShowDxInfoDialog("Wybierz rok podatkowy");
                res = false;
            }
            else
            {
                if (!BrowserCache.IsValid(Init.InitFormBrowserNames.Glowna.LataPodatkowe, false, Settings.RokPodatkowy.Value))
                {
                    this.ShowDxInfoDialog("Zły rok podatkowy");
                    res = false;
                }
            }
            return res;
        }

        private void barManager1_LayoutUpgrade(object sender, DevExpress.Utils.LayoutUpgadeEventArgs e)
        {
            int prev = e.PreviousVersion.AsInt();
            if (prev < 2)
            {
                bbiRokPodatkowy.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
            }
        }

        private void EnsureLink(BarButtonItem item, LinksInfo links)
        {
            foreach (LinkPersistInfo link in links)
            {
                if (link.Item == item)
                {
                    link.Visible = true;
                    return;
                }
            }
            links.Add(new LinkPersistInfo(item));
        }

    }
    
}
